#include"StringPool.h"
#include"variable.h"
#include"RelationalFeature.h"
#include"Util.h"
using namespace std;

RelationalFeature::RelationalFeature(){
	values = NULL;
	name = NULL;
}

RelationalFeature::RelationalFeature(int size, std::string* declaration, FILE* reader){
	values = new vector<vector<string*>*>();
	vector<string*>* declist = Util::split(declaration, ' ');
	string tmp = (*(*declist)[2]);
	name = pool->get(tmp);
	char cstr[1000000];
	for(int i=0;i<size;i++){
		fgets(cstr, 1000000, reader);
		int str_len = (int)(strlen(cstr));
		cstr[str_len - 1] = '\0';
		tmp = string(cstr);
		tmp = tmp.substr(2);
		vector<string*>* value = Util::split(&tmp, ' ');
		values->push_back(value);
	}
	for(vector<string*>::size_type i=0;i<declist->size();i++){
		pool->push_back((*declist)[i]);
	}
	delete(declist);
}

RelationalFeature::~RelationalFeature(){
	if(name != NULL){
		pool->push_back(name);
	}
	if(values != NULL){
		vector<vector<string*>*>::iterator iter;
		for(iter = values->begin(); iter !=values->end(); iter++){
			vector<string*>* v = *iter;
			vector<string*>::iterator iter1;
			for(iter1 = v->begin(); iter1 != v->end(); iter1++){
				pool->push_back(*iter1);
			}
			delete(*iter);
		}
		delete(values);
	}
	name = NULL;
	values = NULL;
}

string RelationalFeature::getFeature(int firstIndex, int secondIndex){
	string result;
	if(firstIndex == 0 || secondIndex == 0){
		result = (*name) + "=NULL";
	}
	else{
		result = (*name) + "=";
		vector<string*>* v = (*values)[firstIndex-1];
		result += (*(*v)[secondIndex-1]);
	}
	return result;
}

void RelationalFeature::writeObject(ObjectWriter &out){
	out.writeString(name);
	out.writeVector(*values);
}

bool RelationalFeature::readObject(ObjectReader &in){
	name = in.readString();
	if(*name == "$end5"){
		return false;
	}
	in.readVector(*values);
	return true;
}
